package com.dkakunsi.monev.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.dkakunsi.monev.entity.Indikator;
import com.dkakunsi.monev.entity.Kegiatan;
import com.dkakunsi.monev.entity.RealisasiIndikator;
import com.dkakunsi.monev.util.MonevDataException;

@Repository("RealisasiFisikHibernateRepository")
public class RealisasiIndikatorDao extends GenericDao<RealisasiIndikator> {
	@SuppressWarnings("unchecked")
	public List<RealisasiIndikator> get(Indikator indikator) throws MonevDataException {
		Query query = getSession().createQuery("SELECT r FROM RealisasiIndikator r WHERE r.indikator = :indikator");
		query.setParameter("indikator", indikator);

		return checkNull(query.list());
	}
	
	@Override
	public void save(RealisasiIndikator r) {
		super.save(isExist(r));
	}
	
	@SuppressWarnings("unchecked")
	public RealisasiIndikator isExist(RealisasiIndikator r) {
		Query query = getSession().createQuery("SELECT r FROM RealisasiIndikator r WHERE r.indikator = :indikator AND r.bulan = :bulan");
		query.setParameter("indikator", r.getIndikator());
		query.setParameter("bulan", r.getBulan());
		
		try {
			List<RealisasiIndikator> ls = checkNull(query.list());
			if(ls.size() <= 0)
				throw new MonevDataException();
			
			RealisasiIndikator ri = ls.get(0);
			ri.setJumlah(r.getJumlah());
			return ri;
		} catch (MonevDataException e) {
			return r;
		}
	}

	@SuppressWarnings("unchecked")
	public List<RealisasiIndikator> get(Kegiatan k) throws MonevDataException {
		Query query = getSession().createQuery("SELECT r FROM RealisasiIndikator r WHERE r.indikator.kegiatan = :kegiatan ORDER BY r.bulan");
		query.setParameter("kegiatan", k);

		return checkNull(query.list());
	}

	@SuppressWarnings("unchecked")
	public List<RealisasiIndikator> get(Kegiatan k, int bulan) throws MonevDataException {
		Query query = getSession().createQuery("SELECT r FROM RealisasiIndikator r WHERE r.indikator.kegiatan = :kegiatan AND r.bulan = :bulan");
		query.setParameter("kegiatan", k);
		query.setParameter("bulan", bulan);

		return checkNull(query.list());
	}
	
	public RealisasiIndikator get(Indikator i, int bulan) throws MonevDataException {
		Query query = getSession().createQuery("SELECT r FROM RealisasiIndikator r WHERE r.indikator = :indikator AND r.bulan = :bulan");
		query.setParameter("indikator", i);
		query.setParameter("bulan", bulan);

		return checkNull((RealisasiIndikator)query.uniqueResult());
	}
}
